<script setup lang="ts">
import {
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
  ElMessageBox,
  ElDialog,
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  FormInstance,
  FormRules,
  ElNotification
} from 'element-plus'
import { useCache } from '@/hooks/web/useCache'
import { resetRouter } from '@/router'
import { useRouter } from 'vue-router'
import { ref, reactive, unref } from 'vue'
import { loginOutApi } from '@/api/login'
import { updatePasswordApi } from '@/api/user'
import { useDesign } from '@/hooks/web/useDesign'
import { useEmitt } from '@/hooks/web/useEmitt'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { usePermissionStore } from '@/store/modules/permission'
import { useSessionStore } from '@/store/modules/session'

const tagsViewStore = useTagsViewStore()
const permissionStore = usePermissionStore()
const sessionStore = useSessionStore()

const { getPrefixCls } = useDesign()

const prefixCls = getPrefixCls('user-info')

const { wsCache } = useCache()

const { replace } = useRouter()

const { emitter } = useEmitt()

const loading = ref<boolean>(false)
// password
const passwordDialogVisible = ref<boolean>(false)
const passwordFormRef = ref<FormInstance>()
const passwordInstance = reactive({
  old_password: '',
  password: '',
  confirm_password: ''
})
const passwordRules = reactive<FormRules>({
  old_password: [{ required: true, message: '请输入原密码' }],
  password: [{ required: true, message: '请输入新密码' }],
  confirm_password: [{ required: true, message: '请再次输入新密码' }]
})

const updatePasswordAction = () => {
  passwordDialogVisible.value = true
  unref(passwordFormRef)?.resetFields()
}

const onPasswordConfirm = () => {
  unref(passwordFormRef)?.validate(async (isValid) => {
    if (isValid) {
      // update password
      const res = await updatePasswordApi(passwordInstance)
      if (res) {
        ElNotification.success('密码修改成功！')
        passwordDialogVisible.value = false

        setTimeout(() => {
          logoff()
        }, 800)
      }
    }
  })
}

// reader
const readerDialogVisible = ref<boolean>(false)
const readerInstance = reactive({
  reader_service: ''
})
const readerRules = reactive<FormRules>({
  reader_service: [{ required: true, message: '请输入会员卡阅读器地址' }]
})

// printer
const printerDialogVisible = ref<boolean>(false)
const printerInstance = reactive({
  printer_service: ''
})
const printerRules = reactive<FormRules>({
  printer_service: [{ required: true, message: '请输入打印服务地址' }]
})

const getReaderService = () => wsCache.get('reader_service') || 'http://127.0.0.1:9600'

const getPrinterService = () => wsCache.get('printer_service') || 'http://127.0.0.1:9600'

const updateReaderServiceAction = () => {
  readerDialogVisible.value = true
  readerInstance.reader_service = getReaderService()
}

const updatePrinterServiceAction = () => {
  printerDialogVisible.value = true
  printerInstance.printer_service = getPrinterService()
}

const onReaderConfirm = () => {
  wsCache.set('reader_service', readerInstance.reader_service)
  emitter.emit('ReaderServiceChanged')
  readerDialogVisible.value = false
}

const onPrinterConfirm = () => {
  wsCache.set('printer_service', printerInstance.printer_service)
  emitter.emit('PrinterServiceChanged')
  printerDialogVisible.value = false
}

const logoff = () => {
  const reader_service = getReaderService()
  const printer_service = getPrinterService()
  wsCache.clear()
  tagsViewStore.delAllViews()
  resetRouter() // 重置静态路由表
  permissionStore.setIsAddRouters(false)
  wsCache.set('reader_service', reader_service)
  wsCache.set('printer_service', printer_service)

  replace('/login')
}

const loginOut = () => {
  ElMessageBox.confirm('是否退出系统?', '温馨提示', {
    type: 'warning'
  })
    .then(async () => {
      const res = await loginOutApi().catch(() => {})
      if (res) {
        logoff()
      }
    })
    .catch(() => {})
}
</script>

<template>
  <div>
    <ElDropdown :class="prefixCls" trigger="click">
      <div class="flex items-center">
        <img
          src="@/assets/imgs/avatar.jpg"
          alt=""
          class="w-[calc(var(--logo-height)-25px)] rounded-[50%]"
        />
        <span class="<lg:hidden text-14px pl-[5px] text-[var(--top-header-text-color)]">{{
          sessionStore.getLoginName
        }}</span>
      </div>
      <template #dropdown>
        <ElDropdownMenu>
          <ElDropdownItem>
            <div @click="updatePasswordAction">修改密码</div>
          </ElDropdownItem>
          <ElDropdownItem divided>
            <div @click="updateReaderServiceAction">阅读器地址</div>
          </ElDropdownItem>
          <ElDropdownItem divided>
            <div @click="updatePrinterServiceAction">打印服务</div>
          </ElDropdownItem>
          <ElDropdownItem divided>
            <div @click="loginOut">退出系统</div>
          </ElDropdownItem>
        </ElDropdownMenu>
      </template>
    </ElDropdown>

    <ElDialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="500px"
      draggable
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <ElForm
        ref="passwordFormRef"
        :model="passwordInstance"
        label-width="100"
        :rules="passwordRules"
      >
        <ElFormItem label="原密码" prop="old_password">
          <ElInput
            v-model="passwordInstance.old_password"
            type="password"
            show-password
            maxlength="20"
          />
        </ElFormItem>
        <ElFormItem label="新密码" prop="password">
          <ElInput
            v-model="passwordInstance.password"
            type="password"
            show-password
            maxlength="20"
          />
        </ElFormItem>
        <ElFormItem label="确认密码" prop="confirm_password">
          <ElInput
            v-model="passwordInstance.confirm_password"
            type="password"
            show-password
            maxlength="20"
          />
        </ElFormItem>
      </ElForm>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onPasswordConfirm" :loading="loading">确认</el-button>
        </span>
      </template>
    </ElDialog>

    <ElDialog
      v-model="readerDialogVisible"
      title="会员卡阅读器地址"
      width="500px"
      draggable
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <ElForm :model="readerInstance" label-width="100" :rules="readerRules">
        <ElFormItem label="地址" prop="reader_service">
          <ElInput v-model="readerInstance.reader_service" maxlength="50" />
        </ElFormItem>
      </ElForm>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="readerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onReaderConfirm" :loading="loading">确认</el-button>
        </span>
      </template>
    </ElDialog>

    <ElDialog
      v-model="printerDialogVisible"
      title="打印服务地址"
      width="500px"
      draggable
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <ElForm :model="printerInstance" label-width="100" :rules="printerRules">
        <ElFormItem label="地址" prop="printer_service">
          <ElInput v-model="printerInstance.printer_service" maxlength="50" />
        </ElFormItem>
      </ElForm>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="printerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onPrinterConfirm" :loading="loading">确认</el-button>
        </span>
      </template>
    </ElDialog>
  </div>
</template>
